/*
 * @Descripttion:
 * @version:
 * @Author: hujianli
 * @Date: 2022-07-03 09:21:53
 * @LastEditors: hujianli
 * @LastEditTime: 2022-07-03 13:03:50
 */
package main

import (
	"bufio"
	"fmt"
	"log"
	"net/http"
	"os"
	"text/template"
)

type Guestbook struct {
	SignatureCount int
	Signatures     []string
}

/**
 * @name: check
 * @msg: 检测err
 * @param {error} err
 * @return {*}
 */
func check(err error) {
	if err != nil {
		log.Fatal(err)
	}
}

func getStrings(fileName string) []string {
	var lines []string
	file, err := os.Open(fileName)
	if os.IsNotExist(err) {
		return nil
	}
	check(err)
	defer file.Close()
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}
	check(scanner.Err())
	return lines
}

func newHandler(writer http.ResponseWriter, request *http.Request) {
	html, err := template.ParseFiles("new.html")
	check(err)
	err = html.Execute(writer, nil)
	check(err)

}

func viewHandler(writer http.ResponseWriter, request *http.Request) {
	signatures := getStrings("signatures.txt")
	fmt.Printf("%#v\n", signatures)
	html, err := template.ParseFiles("view.html")
	check(err)
	guestboooks := Guestbook{
		SignatureCount: len(signatures),
		Signatures:     signatures,
	}
	err = html.Execute(writer, guestboooks)
	check(err)

}

func createHandler(writer http.ResponseWriter, request *http.Request) {
	signatures := request.FormValue("signature")
	// fmt.Printf("submit : %#v\n", signatures)
	// _, err := writer.Write([]byte(signatures))
	// check(err)

	options := os.O_WRONLY | os.O_APPEND | os.O_CREATE
	file, err := os.OpenFile("signatures.txt", options, os.FileMode(0600)) //打开文件
	check(err)
	_, err = fmt.Fprintln(file, signatures)
	check(err)
	err = file.Close() // 关闭文件
	check(err)
	http.Redirect(writer, request, "/guestbook", http.StatusFound)
}

func main() {
	http.HandleFunc("/guestbook", viewHandler)
	http.HandleFunc("/guestbook/new", newHandler)
	http.HandleFunc("/guestbook/create", createHandler)
	err := http.ListenAndServe("localhost:8080", nil)
	log.Fatal(err)

}
